<template>
  <div class="content-box mtop-20">
    <top-info
      tagName="歌手"
      :rightStyle="{ 'lineHeight': '50px' }"
      :playList="artist"   
    >
      <!-- 图片 -->
      <template #picture>
        <img
          class="img-percent"
          v-if="isList"
          v-lazy="`${artist.cover}?param=300y300`"
        >
      </template>
      <!-- 按钮 -->
      <template #btns>
        <a-button class="mright-10 br-30 play-all" @click="subOne(1)" v-show="subShow">
          <a-icon class="font-16" type="folder-add" /> 收藏</a-button>
        <a-button class="mright-10 br-30 play-all" @click="subOne(0)" v-show="!subShow">
          <a-icon class="font-16" type="check" /> 已收藏</a-button>
        <a-button v-if="userId" class="br-30 play-all" @click="userDetail">
          <a-icon class="font-16" type="user" /> 个人主页</a-button>
      </template>
      <!-- 其他描述信息 -->
      <template>
        <div v-if="isList" class="font-16">
          <span>单曲数：{{ artist.musicSize }}</span>
          <span class="mleft-20">专辑数：{{ artist.albumSize }}</span>
          <span class="mleft-20">MV数：{{ artist.mvSize }}</span>
        </div>
      </template>
    </top-info>
    <Tabs ref="tab" :tabList="tabList" @target="target" />
    <a-spin :spinning="spinning" tip="努力加载中...">
      <a-icon slot="indicator" type="loading" style="font-size: 40px" spin />
      <keep-alive>
        <div class="singer-album" v-if="modules === 'album'">
          <!-- 热门50首 -->
          <AlbumList
            albumName="热门50首"
            :albumSong="hotList"
            v-show="hotList.length"
          />
          <!-- 专辑 -->
          <AlbumList
            v-for="item in albumList"
            :key="item.album.id"
            :albumSong="item.songs"
            :albumId="item.album.id"
            :albumName="item.album.name"
            :albumImg="item.album.picUrl"
          />
          <!-- 加载更多 -->
          <LoadMore
            ref="loadMore"
            :more="more"
            :delayTime="1000"
            @scrollMore="scrollByList"
          />
        </div>
        <div class="singer-mv"  v-else-if="modules === 'MV'">
          <MvList
            v-for="item in mvs"
            :key="item.id"
            :playcount="item.playCount"
            :cover="item.imgurl"
            :videoAuthor="[item.artist]"
            :videoTitle="item.name"
            :durationms="item.duration"
            @goDetail="event => gomvDetail(event, item.id)"
          />
          <LoadMore ref="loadMore" :more="mvmore" @scrollMore="scrollByList" />
        </div>
        <div class="singer-del" v-else-if="modules === 'singerDetail'">
          <SingerDetail :detail="detail" />
        </div>
        <div class="similar-singer" v-else-if="modules === 'similarSinger'">
          <ContentCard
            v-if="simiList && simiList.length"
            :dataList="simiList"
            @goDetail="goDetail"
          />
          <Empty v-else description="无相似歌手" />
        </div>
      </keep-alive>
    </a-spin>
  </div>
</template>

<script>
import {
  artistDetail,
  hotSongs,
  artistAlbum,
  albumInfo,
  singerDetail,
  simiArtist,
  subList,
  singerMV
} from '@/api/detail';
import { subArtist } from '@/api';
import mixin from '@/mixins/mixin';
import SingerDetail from './SingerDetail';
import Empty from '@/components/Library/Empty';
import Tabs from '@/components/Content/Tabs';
import AlbumList from '@/components/Content/AlbumList';
import TopInfo from '@/components/Detail/TopInfo';
import MvList from '@/components/Content/MvList';
import ContentCard from '@/components/Content/ContentCard';
// 加载更多组件
import LoadMore from '@/components/Library/LoadingMore';
import { Spin } from 'ant-design-vue';

export default {
  name: 'artistDetail',

  mixins: [mixin],

  components: {
    TopInfo,
    Tabs,
    Empty,
    MvList,
    SingerDetail,
    ContentCard,
    LoadMore,
    AlbumList,
    ASpin: Spin
  },

  data() {
    return {
      // 判断展示对应模块,默认为专辑
      modules: 'album',
      artist: {},
      userId: '',
      // 加载更多
      more: true,
      // mv加载更多
      mvmore: true,
      // 收藏按钮显示隐藏
      subShow: true,
      // 控制loading显示隐藏
      spinning: true,
      // 滚动次数
      scroll: 0,
      tabList: [{
        tabName: '专辑',
        isActive: true,
        id: 'album'
      }, {
        tabName: 'MV',
        isActive: false,
        id: 'MV'
      }, {
        tabName: '歌手详情',
        isActive: false,
        id: 'singerDetail'
      }, {
        tabName: '相似歌手',
        isActive: false,
        id: 'similarSinger'
      }],
      // 歌手热门歌曲50首
      hotList: [],
      // 专辑歌曲
      // albumSongs: [],
      // 歌手专辑
      albumList: [],
      // 歌手详情
      detail: [],
      // 歌手mv
      mvs: [],
      // 相似歌手
      simiList: [],
      // 专辑接口参数
      params: {
        id: this.$route.query.id,
        limit: 10,
        offset: 0,
        timestamp: new Date().getTime()
      },
      mvparams: {
        id: this.$route.query.id,
        limit: 20,
        offset: 0,
        timestamp: new Date().getTime()
      }
    }
  },

  computed: {
    artistId() {
      return this.$route.query.id
    },
    isList() {
      return this.artist && this.artist.id;
    },
    // 是否有专辑
    isAlbum() {
      return this.albumList && this.albumList.length;
    },
    // 是否有歌手详情
    isDetail() {
      return this.detail && this.detail.length;
    },
    // 是否有相似歌手
    isSimi() {
      return this.simiList && this.simiList.length;
    }
  },

  watch: {
    // 监听路由id调用接口
    '$route.query.id': {
      handler(value, oldValue) {
        console.log(value, oldValue)
        // 说明两次都是同一个歌手,那么就不再重新请求接口了
        if (value === oldValue) return;
        // 重置模块为专辑
        this.modules = 'album';
        // 显示loading
        this.spinning = true;
        // 重置tab选中项
        this.tabList.find(item => item.isActive).isActive = false;
        this.tabList[0].isActive = true;
        // 重置专辑列表
        this.albumList = [];
        // 重置歌手详情和相似歌手数据,
        // 跳转到另一个歌手需要重新调用接口,之前做过判断,有值时不会再次调用接口刷新
        this.simiList = [];
        this.detail = [];
        // 这里需要手动赋值,不然拿到的是上一个歌手id
        this.params.id = this.artistId;
        this.params.offset = 0;
        this.scroll = 1;
        console.log(this.scroll);
        this.getArtistAlbum();
        this.$forceUpdate();
      },
      // 必须加上,不然不会立刻监听id变化
      // immediate: true
    }
  },

  created() {
    // this.getArtistDetail();
    // this.getHotSongs();
    // this.getSubList();
    // 第一次进入不要loading,因为loadingMore组件事件第一次进入不会调用专辑接口
    this.spinning = false;
    // this.$store.commit('main/ISPLAYED', false);
  },

  methods: {
    async getArtistDetail() {
      const res = (await artistDetail(this.artistId)).data;
      this.artist = Object.freeze(res.data.artist);
      if (res.data.user && res.data.user.userId) {
        this.userId = res.data.user.userId;
      } else {
        // 没有id需要重置,不然个人主页按钮不会隐藏
        this.userId = '';
      }
      this.$store.commit('main/LOADING', false);
    },
    // 获取歌手热门50首
    async getHotSongs() {
      const res = (await hotSongs(this.artistId)).data;
      this.hotList = Object.freeze(res.songs);
    },
    // 获取歌手专辑
    async getArtistAlbum() {
      const res = (await artistAlbum(this.params)).data;
      const albums = [];
      albums.push(...res.hotAlbums);
      this.more = res.more;
      if (this.scroll <= 1) {
        this.$store.commit('main/LOADING', true);
      }
      // 存放多个接口的结果
      let axiosList = res.hotAlbums.map(item => {
        return albumInfo(item.id);
      });
      Promise.all(axiosList).then(res => {
        const list = res.map(item => item.data)
        this.albumList.push(...list);
        this.spinning = false;
      }).finally(() => {
        if (this.scroll > 1) return;
        this.$store.commit('main/LOADING', false);
        // 重新调用接口
        this.getArtistDetail();
        this.getHotSongs();
        this.getSubList();
      });
    },
    // 获取歌手MV
    async getSingerMV() {
      const res = (await singerMV(this.mvparams)).data;
      this.mvs.push(...Object.freeze(res.mvs));
      this.mvmore = res.hasMore;
    },
    // 获取歌手详情
    async getSingerDetail() {
      if (this.detail && this.detail.length) return;
      const res = (await singerDetail(this.artistId)).data;
      const d = [];
      d.push({
        ti: `${this.artist.name}简介`,
        txt: res.briefDesc
      }, ...res.introduction);
      this.detail = d.map(item => {
        return {
          ti: item.ti,
          txt: item.txt.split('\n')
        }
      });
      console.log(this.detail);
      this.spinning = false;
    },
    // 获取相似歌手
    async getSimiArtist() {
      if (this.simiList && this.simiList.length) return;
      const res = (await simiArtist(this.artistId)).data;
      this.simiList = Object.freeze(res.artists);
      this.spinning = false;
    },
    userDetail() {
      this.$router.push({
        name: 'userdetail',
        query: {
          id: this.userId
        }
      })
    },
    // 相似歌手跳转
    goDetail(id) {
      this.$router.push({
        name: 'artistdetail',
        query: { id }
      });
    },
    // gomvDetail(event, id) {
    //   const { aid } = event.target.dataset;
    //   if (aid) return;
    //   this.$router.push({
    //     name: 'videodetail',
    //     query: {
    //       mid: id
    //     }
    //   })
    // },
    // 下拉加载更多
    scrollByList() {
      if (this.modules === 'album') {
        this.params.offset
          = this.scroll++ * this.params.limit;
        this.getArtistAlbum();
      }
      if (this.modules === 'MV') {
        this.mvparams.offset
          = this.scroll++ * this.mvparams.limit;
        this.getSingerMV();
      }
    },
    // 收藏或取消收藏歌手
    async subOne(t) {
      const res = await subArtist({
        id: this.artistId,
        t
      });
      if (res.data.code === 200) {
        
        this.subShow = !this.subShow;
        if (t) {
          this.$message.success('收藏成功');
          return;
        }
        this.$message.success('取消收藏成功');
      } else {
        this.$message.error('收藏失败');
      }
    },
    // 获取收藏歌手列表
    async getSubList() {
      const res = (await subList()).data;
      const isSub
        = res.data.findIndex(item => item.id == this.artistId);
      // 说明收藏过该歌手
      if (isSub !== -1) this.subShow = false;
    },
    // 点击tab栏切换
    target(name) {
      this.modules = name;
      switch(name) {
        // 相似歌手
        case 'similarSinger':
          if (!this.isSimi) {
            this.spinning = true;
          }
          if (this.scroll) this.scroll = 0;
          this.getSimiArtist();
          break;
        case 'MV':

          if (this.scroll) this.scroll = 1;
          this.getSingerMV();
          break;
        // 歌手详情
        case 'singerDetail':
          if (!this.isDetail) {
            this.spinning = true;
          }
          this.getSingerDetail();
          break;
      }
    }
  }
}
</script>

<style lang="less" scoped>
.content-box {
  height: 97%;
}
/deep/ul.tab-list {
  margin-left: 0 !important;
  font-size: 16px;
}
</style>